//
//  GroupInfoViewController.m
//  NuwaRobot
//
//  Created by Kendama on 2017/12/12.
//  Copyright © 2017年 Kendama. All rights reserved.
//

#import "GroupInfoViewController.h"
#import "GroupInfoView.h"
#import "HomeCollectionViewCell.h"
#import "MyInfoTableViewCell.h"
#import "AvatarTableViewCell.h"
#import "GroupMemberViewController.h"
#import "GroupNameViewController.h"
#import "ChooseContactsViewController.h"
#import "GetHuanxinGroupUserListApi.h"
#import "FriendModel.h"

@interface GroupInfoViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) EMGroup *group;
@property (nonatomic, strong) NSString *groupId;
@property(nonatomic,strong) GroupInfoView *containerView;
@property(nonatomic,strong) NSMutableArray *collectionDataSource;
@property(nonatomic,strong) NSMutableArray *allMembersArray;
@property(nonatomic,strong) NSArray *tableDataSource;
@property (nonatomic, strong) UIImagePickerController * imagePicker; // 系统图片框架
@property(nonatomic,copy) NSString *domain;

@end

@implementation GroupInfoViewController

- (instancetype)initWithGroupId:(NSString *)aGroupId
{
    self = [super init];
    if (self) {
        _groupId = aGroupId;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self getGroupMembers];
    [self fetchGroupInfo];
}


#pragma mark -- 点击事件
- (void)didClickMoreButton
{
    GroupMemberViewController *vc = [[GroupMemberViewController alloc] initWithGroup:self.allMembersArray];
    vc.domain = self.domain;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - DataSource
- (void)getGroupMembers
{
//    [self showHudInView:self.view hint:NSLocalizedString(@"loadData", @"Load data...")];
    [SVProgressHUD showWithStatus:@"正在加载中..."];
    GetHuanxinGroupUserListApi *api = [[GetHuanxinGroupUserListApi alloc] initWithDic:@{@"group_id":self.groupId}];
    [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        [SVProgressHUD dismiss];
        NSDictionary *dict = request.responseJSONObject;
        self.domain = dict[@"domain"];
        [self.collectionDataSource removeAllObjects];
        NSArray *array = [NSArray yy_modelArrayWithClass:[FriendModel class] json:dict[@"data"]];
        [self.allMembersArray removeAllObjects];
        [self.allMembersArray addObjectsFromArray:array];
        if (array.count > 6)
        {
            NSRange range = NSMakeRange(0, 6);
            [self.collectionDataSource addObjectsFromArray:[array subarrayWithRange:range]];
        }
        else
        {
            [self.collectionDataSource addObjectsFromArray:array];
        }
        FriendModel *model = [[FriendModel alloc] init];
        [self.collectionDataSource addObjectsFromArray:@[model,model]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.containerView.collectionView reloadData];
        });
    } failure:nil];
}

- (void)fetchGroupInfo
{
    __weak typeof(self) weakSelf = self;
//    [self showHudInView:self.view hint:NSLocalizedString(@"loadData", @"Load data...")];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(){
        EMError *error = nil;
        EMGroup *group = [[EMClient sharedClient].groupManager getGroupSpecificationFromServerWithId:weakSelf.groupId error:&error];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf hideHud];
        });
        
        if (!error) {
            weakSelf.group = group;
//            [weakSelf.containerView.tableView reloadData];
//            [weakSelf.collectionDataSource removeAllObjects];
//            if (group.occupants.count > 6)
//            {
//                NSRange range = NSMakeRange(0, 6);
//                [weakSelf.collectionDataSource addObjectsFromArray:[group.occupants subarrayWithRange:range]];
//            }
//            else
//            {
//                [weakSelf.collectionDataSource addObjectsFromArray:group.occupants];
//            }
//            [weakSelf.collectionDataSource addObjectsFromArray:@[@"",@""]];
            
//            EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:group.groupId type:EMConversationTypeGroupChat createIfNotExist:YES];
//            if ([group.groupId isEqualToString:conversation.conversationId]) {
//                NSMutableDictionary *ext = [NSMutableDictionary dictionaryWithDictionary:conversation.ext];
//                [ext setObject:group.subject forKey:@"subject"];
//                [ext setObject:[NSNumber numberWithBool:group.isPublic] forKey:@"isPublic"];
//                conversation.ext = ext;
//            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
//                [weakSelf.containerView.collectionView reloadData];
                [weakSelf.containerView.tableView reloadData];
//                [weakSelf fetchGroupMembers];
            });
        }
        else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf showHint:NSLocalizedString(@"group.fetchInfoFail", @"failed to get the group details, please try again later")];
            });
        }
        
    });
    
//    [[EMClient sharedClient].groupManager getGroupAnnouncementWithId:_groupId completion:^(NSString *aAnnouncement, EMError *aError) {
//        if (!aError) {
//            [weakSelf.containerView.collectionView reloadData];
//        } else {
//            NSLocalizedString(@"group.fetchAnnouncementFail", @"fail to get announcement");
//        }
//    }];
}

- (void)fetchGroupMembers
{
    GetHuanxinGroupUserListApi *api = [[GetHuanxinGroupUserListApi alloc] initWithDic:@{@"group_id":self.groupId}];
    [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        
    } failure:nil];
//    __weak typeof(self) weakSelf = self;
//    [self showHudInView:self.view hint:NSLocalizedString(@"loadData", @"Load data...")];
//    [[EMClient sharedClient].groupManager getGroupMemberListFromServerWithId:self.groupId cursor:@"" pageSize:10 completion:^(EMCursorResult *aResult, EMError *aError) {
//        [weakSelf hideHud];
//        if (!aError) {
////            weakSelf.showMembers = aResult.list;
////            [weakSelf reloadUI];
//        } else {
//            [weakSelf showHint:NSLocalizedString(@"group.fetchInfoFail", @"failed to get the group details, please try again later")];
//        }
//    }];
}

#pragma mark --- 代理
#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.collectionDataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HomeCollectionViewCell *cell = [HomeCollectionViewCell cellWithCollectionView:collectionView forIndexPath:indexPath];
//    NSArray *titleArray = self.collectionDataSource.firstObject;
//    NSArray *imageArray = self.collectionDataSource.lastObject;
    
//    cell.iconImageView.image = imageWithName(@"head1");
    FriendModel *model = self.collectionDataSource[indexPath.row];
    cell.titleLabel.text = model.nickname;
    NSString *url = [NSString stringWithFormat:@"%@%@",self.domain,model.image];
    [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:imageWithName(@"icon_head")];
    if ([model.nickname isEqualToString:@""])
    {
        cell.titleLabel.text = @"我的机器人";
        cell.iconImageView.image = imageWithName(@"robot_head");
    }
    cell.badgeLabel.hidden = YES;
    cell.titleLabel.hidden = NO;
    if (indexPath.row == self.collectionDataSource.count - 2)
    {
        cell.iconImageView.image = imageWithName(@"addition");
        cell.titleLabel.hidden = YES;
    }
    else if (indexPath.row == self.collectionDataSource.count - 1)
    {
        cell.iconImageView.image = imageWithName(@"reduce");
        cell.titleLabel.hidden = YES;
    }
//    cell.badgeLabel.text = @"2";
    //    cell.backgroundColor = indexPath.row %2 ? [UIColor redColor] : [UIColor blueColor];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ((indexPath.row == self.collectionDataSource.count - 2) || (indexPath.row == self.collectionDataSource.count - 1))
    {
        ChooseContactsViewController *vc = [[ChooseContactsViewController alloc] initWithGroup:self.group];
        if (indexPath.row == self.collectionDataSource.count - 2) // 添加成员
        {
            vc.chooseType = AddMember;
        }
        else if (indexPath.row == self.collectionDataSource.count - 1) // 删除成员
        {
            vc.chooseType = DeleteMember;
        }
        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
        
    }
}

#pragma mark --- tabelview代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = self.tableDataSource[section];
    return array.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.tableDataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return px1920Height(180);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return px1920Height(30);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *titleArray = self.tableDataSource[indexPath.section];
    if (indexPath.section == 0 && indexPath.row == 0)
    {
        AvatarTableViewCell *cell = [AvatarTableViewCell dequeueReusableWithTableView:tableView];
        cell.titleLabel.text = titleArray[indexPath.row];
        cell.avatarImageView.image = imageWithName(@"head1");
        return cell;
    }
    else
    {
        MyInfoTableViewCell *cell = [MyInfoTableViewCell dequeueReusableWithTableView:tableView];
        cell.titleLabel.text = titleArray[indexPath.row];
        if (indexPath.section == 0)
        {
            cell.infoLabel.text = self.group.subject;
        }
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
            UIActionSheet *sheet=[[UIActionSheet alloc]initWithTitle:@"设置头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍摄照片" otherButtonTitles:@"相册", nil] ;
            [sheet showInView:self.view];
        }
        else
        {
            GroupNameViewController *vc = [[GroupNameViewController alloc] initWithGroup:self.group];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    else
    {
        [self clearMessagesAction];
    }
    
}

#pragma mark - 事件处理
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    NSLog(@"buttonindex===%ld",(long)buttonIndex);
    switch (buttonIndex) {
        case 0:
            
        {
            [self formcamera];
            
        }
            break;
        case 1:
            
        {
            [self formphoto];
        }
            break;
            
        default:
            break;
    }
}

-(void)formcamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
        imagePicker.delegate = self;
        imagePicker.allowsEditing=YES;
        _imagePicker = imagePicker;
        if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0)
        {
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                
                [self presentViewController:imagePicker animated:YES completion:^{ }];
            }];
            
        }
        else{
            
            [self.navigationController presentViewController:imagePicker animated:YES completion:^{ }];
        }
    }else{
        
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"设备不可用" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
    }
}
-(void)formphoto
{
    
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    _imagePicker = imagePicker;
    if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0)
    {
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            
            [self presentViewController:imagePicker animated:YES completion:^{ }];
        }];
        
    }
    else{
        
        [self.navigationController presentViewController:imagePicker animated:YES completion:^{ }];
    }
}

#pragma mark - private methods -
- (UIImagePickerController *)creatImagePickVCWithSourceType:(UIImagePickerControllerSourceType)sourceType{
    
    UIImagePickerController *imagePickVC = [[UIImagePickerController alloc]init];
    
    //设置选取的照片是否可编辑
    imagePickVC.allowsEditing = YES;
    if (sourceType == UIImagePickerControllerSourceTypeCamera) {
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            NSLog(@"模拟器无法打开相机");
            return nil;
        }
    }
    //设置相册呈现的样式
    imagePickVC.sourceType =  UIImagePickerControllerSourceTypeCamera;
    imagePickVC.delegate = self;
    
    if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0)
    {
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            
            [self presentViewController:imagePickVC animated:YES completion:^{ }];
        }];
        
    }
    else{
        
        [self.navigationController presentViewController:imagePickVC animated:YES completion:^{ }];
    }
    
    return imagePickVC;
}

#pragma mark - UIImagePickerControllerDelegate
// 完成选择
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [_imagePicker dismissViewControllerAnimated:YES completion:nil];
    UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];  // 取出被编辑的图片
    NSData * imageData = UIImageJPEGRepresentation(image, 1.0f);
    [[NSFileManager defaultManager]removeItemAtPath:PicPath(UID) error:nil];
    
    if (imageData.length > 100 * 1024) {
        if (imageData.length > 1000 * 1024) {
            [UIImageJPEGRepresentation(image, 0.2f) writeToFile:PorPath atomically:YES];
        } else {
            [UIImageJPEGRepresentation(image, 0.4f) writeToFile:PorPath atomically:YES];
        }
    } else {
        [UIImageJPEGRepresentation(image, 1.0f) writeToFile:PorPath atomically:YES];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    
    //    SetUserInfoApi * setApi = [[SetUserInfoApi alloc] initWithInfo:@{@"image":PorPath}];
    //    [setApi dtDefaultInterceptStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
    //        if ([[request responseJSONObject][@"errcode"] intValue] == 0) {
    //            GetUserInfoApi * userInfoApi = [[GetUserInfoApi alloc] init];
    //            [userInfoApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
    //                [userInfoApi analyseResponseObject];
    //                [self.tableView reloadData];
    //                [SVProgressHUD showSuccessWithStatus:MyNSLocalizedString(@"修改成功")];
    //                [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUserInfo" object:nil];
    //            } failure:^(YTKBaseRequest *request) {
    //                [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"请求超时")];
    //            }];
    //        }
    //    } failure:nil];
    
}

// 取消选择
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [_imagePicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)clearMessagesAction
{
    __weak typeof(self) weakSelf = self;
    [EMAlertView showAlertWithTitle:@"提示"
                            message:@"是否删除历史聊天记录"
                    completionBlock:^(NSUInteger buttonIndex, EMAlertView *alertView) {
                        if (buttonIndex == 1) {
                            [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATIONNAME_DELETEALLMESSAGE object:weakSelf.groupId];
                        }
                    } cancelButtonTitle:@"取消"
                  otherButtonTitles:@"确定", nil];
}

#pragma mark --- 懒加载
- (GroupInfoView *)containerView
{
    if(!_containerView)
    {
        UIView *superView = self.view;
        _containerView = [[GroupInfoView alloc]init];
        [superView addSubview:_containerView];
        _containerView.collectionView.dataSource = self;
        _containerView.collectionView.delegate = self;
        _containerView.tableView.delegate = self;
        _containerView.tableView.dataSource = self;
        [_containerView.moreButton addTarget:self action:@selector(didClickMoreButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _containerView;
}

- (NSMutableArray *)collectionDataSource
{
    if(!_collectionDataSource)
    {
        _collectionDataSource = [[NSMutableArray alloc]init];
    }
    return _collectionDataSource;
}

- (NSArray *)tableDataSource
{
    if(!_tableDataSource)
    {
        _tableDataSource = @[@[@"家庭头像",@"家庭名称"],@[@"清空聊天记录"]];
    }
    return _tableDataSource;
}

- (NSMutableArray *)allMembersArray
{
    if(!_allMembersArray)
    {
        _allMembersArray = [[NSMutableArray alloc]init];
    }
    return _allMembersArray;
}



- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.left.right.bottom.mas_equalTo(superView);
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setNavigationStyle
{
    [self setNavigationBarTitle:@"群组信息"];
}

@end
